<?php
//error_reporting(E_ALL);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_model.delivery.cdn_delivery_explain");
\ns_core\m_load::load_np("np_http_curl.class.php");
class delivery extends \ns_model\delivery\cdn_delivery_explain
{

    private $c2_task_info = null;

    private $asst_info = null;

    /**
     * CDN注入统一解释器入口
     * @param $info array(
     *                      'c2_info'=>array(C2信息),
     *                      'video_info'=>array(
     *                          'base_info' => VIDEO信息
     *                          'ex_info'  => 扩展信息
     *                       ),
     *                      'index_info'=>array(
     *                          'base_info' => INDEX信息,
     *                          'ex_info' => 扩展信息,
     *                      ),
     *                      'media_info'=>array(
     *                          'base_info' => MEDIA信息
     *                          'ex_info' => 扩展信息
     *                      ),
     *                  )
     */
    public function explain($info = array())
    {
        if(isset($info['c2_info']) && is_array($info['c2_info']) && !empty($info['c2_info']))
        {
            //return \m_config::return_data("1","C2任务数据错误，执行注入CDN失败");
            $this->c2_task_info = isset($info['c2_info']) ? $info['c2_info'] : $this->c2_info;
            $this->video_info = isset($info['video_info']) ? $info['video_info'] : $this->video_info;
            $this->index_info = isset($info['index_info']) ? $info['index_info'] : $this->index_info;
            $this->media_info = isset($info['media_info']) ? $info['media_info'] : $this->media_info;
        }
        else
        {
            $this->c2_task_info = $this->c2_info;
        }
        //做兼容
        $this->asst_info = array(
            'video' => $this->video_info,
            'index' => $this->index_info,
            'media' => $this->media_info,
        );
        $fun_name = (string)$this->c2_task_info['nns_type'];
        return $this->$fun_name();
    }

    /**
     * CDN注入统一发送器入口
     * 按项目进行自定义发送处理
     * @param $data array(
            'nns_task_type' =>类型,
            'nns_task_id' => 任务ID,
            'nns_task_name' => 任务名称,
            'nns_action' => 行为动作，
            'nns_content' => 注入XML内容
     * );
     * @return array('ret','reason');
     */
    public function execute($data)
    {
        $data['nns_id'] = np_guid_rand();
        $task = \m_config::write_cdn_import_execute_log($this->str_sp_id,$data['nns_task_type'],$data['nns_action'],$data['nns_content']);
        if($task['ret'] != 0)
        {
            return $task;
        }
        $local_url = $task['data_info']['base_dir'];
        $obj_curl = new np_http_curl_class();
        
        $arr_header = array(
            "Content-Type: text/plain; charset=utf-8",
        );

        $obj_curl->post($this->arr_sp_config['nns_config']['cdn_send_mode_url'], $data['nns_content'],$arr_header,60);
        $curl_info = $obj_curl->curl_getinfo();

        if($curl_info['http_code'] == '200')
        {
//             return _comm_make_return_data(1,'[访问切片转码失败,CURL接口地址]：'.$arr_sp_config['nns_config']['cdn_send_mode_url'].'[HTTP状态码]：'.$curl_info['http_code'].'[HTTP错误]：'.$obj_curl->curl_error(),'参数：'.var_export($data,true));
            $re_code = 0;
            $re_resaon = '发送成功';
        }
        else
        {
//             return _comm_make_return_data(0,'[访问切片转码成功,CURL接口地址]：'.$arr_sp_config['nns_config']['cdn_send_mode_url'].'参数'.var_export($data,true),$curl_data);
            $re_code = -1;
            $re_resaon = '发送失败';
        }
        $data['nns_url'] = $local_url;
        $data['nns_result'] = $re_code;
        $data['nns_result_fail_reason'] = $re_resaon;
        $build_c2 = $this->build_c2_log($data);
        if($build_c2['ret'] != 0)
        {
            return $build_c2;
        }
        return $this->is_ok($this->c2_task_info,$re_code,$re_resaon);
    }

	private function video()
    {
        return m_config::return_data(1,'不注入主媒资信息');
	}
	
    private function index()
	{
	    return m_config::return_data(1,'不注入分集信息');
	}


    private function media()
	{
	    if ($this->c2_task_info['nns_action'] === 'destroy')
	    {
	        return $this->media_destroy('DELETE');
	    }
	    else
	    {
	        $action = 'REGIST';
	    }
	    global $g_bk_web_url;
	    $bk_web_url = $g_bk_web_url;
	    unset($g_bk_web_url);
	    $bk_web_url = trim(trim(trim($bk_web_url,'\\'),'/'));
	    $bk_web_url.="/v2/ns_api/gdgd_xiaole/delivery/coship/notify.php";

        $info = $this->asst_info;
	    if(isset($this->arr_sp_config['nns_config']['disabled_clip']) && (int)$this->arr_sp_config['nns_config']['disabled_clip'] !== 2 && (int)$this->arr_sp_config['nns_config']['disabled_clip'] !== 3)
	    {
	        $info['media']['base_info']['nns_url'] = ltrim((trim($this->c2_task_info['nns_file_path'])),'/');
	        if(isset($this->arr_sp_config['nns_config']['media_ftp']) && !empty($this->arr_sp_config['nns_config']['media_ftp']))
	        {
	            $this->arr_sp_config['nns_config']['media_ftp'] = rtrim((trim($this->arr_sp_config['nns_config']['media_ftp'])),'/');
	            if (stripos($info['media']['base_info']['nns_url'], 'http://') === FALSE && stripos($info['media']['base_info']['nns_url'], 'ftp://') === FALSE)
	            {
	                $info['media']['base_info']['nns_url'] = $this->arr_sp_config['nns_config']['media_ftp'].'/'.$info['media']['base_info']['nns_url'];
	            }
	        }
	    }
	    else
	    {
	        $info['media']['base_info']['nns_url'] = ltrim((trim($info['media']['base_info']['nns_url'])),'/');
	        if(isset($this->arr_sp_config['nns_config']['media_ftp']) && !empty($this->arr_sp_config['nns_config']['media_ftp']))
	        {
	            $this->arr_sp_config['nns_config']['media_ftp'] = rtrim((trim($this->arr_sp_config['nns_config']['media_ftp'])),'/');
	            if (stripos($info['media']['base_info']['nns_url'], 'http://') === FALSE && stripos($info['media']['base_info']['nns_url'], 'ftp://') === FALSE)
	            {
	                $info['media']['base_info']['nns_url'] = $this->arr_sp_config['nns_config'].'/'.$info['media']['base_info']['nns_url'];
	            }
	        }
	    }

        //问题说明：广州孝乐专区-现场转码后片源路径改变需要从新对接获取
        //修改说明：从临时片源TS文件路径关系表中查询数据，如果存在数据就替换，反之不替换
        //修改人员：kan.yang@starcor.cn
        //修改时间：2018-02-07 22:33:00
        $str_table_name = 'nns_ls_media_path_relation';
        $str_sql = "SELECT COUNT(1) total FROM INFORMATION_SCHEMA.TABLES WHERE `TABLE_NAME` = '" . $str_table_name . "'";
        $arr_table_exists = nl_db_get_one($str_sql,\m_config::get_dc()->db());
        if(is_array($arr_table_exists) && $arr_table_exists['total'] > 0)
        {
            $str_sql = "SELECT * FROM " . $str_table_name . " WHERE nns_id = '" . $this->asst_info['media']['cdn_info'] . "'";
            $arr_media_info = nl_db_get_one($str_sql,\m_config::get_dc()->db());

            if(is_array($arr_media_info) && !empty($arr_media_info))
            {
                $str_comm_url = get_config_v2('g_ls_media_path');
                //$info['media']['base_info']['nns_url'] = $str_comm_url . '/' . $info['media']['base_info']['nns_cp_id'] . '/' . $arr_media_info['nns_new_url'];
                $info['media']['base_info']['nns_url'] = $str_comm_url . '/' . $arr_media_info['nns_new_url'];
            }
        }

	    $arr_parse_url = parse_url($info['media']['base_info']['nns_url']);
	    $temp_url = '';
	    $temp_username = (isset($arr_parse_url['user']) && strlen($arr_parse_url['user']) >0) ? $arr_parse_url['user'] : '';
	    $temp_password = (isset($arr_parse_url['pass']) && strlen($arr_parse_url['pass']) >0) ? $arr_parse_url['pass'] : '';
	    if(isset($arr_parse_url['scheme']) && strlen($arr_parse_url['scheme'])>0)
	    {
	        $temp_url.=$arr_parse_url['scheme']."://";
	    }
	    if(isset($arr_parse_url['host']) && strlen($arr_parse_url['host'])>0)
	    {
	        $temp_url.=$arr_parse_url['host'];
	    }
	    if(isset($arr_parse_url['port']) && strlen($arr_parse_url['port'])>0)
	    {
	        $temp_url.=":".$arr_parse_url['port'];
	    }
	    if(isset($arr_parse_url['path']) && strlen($arr_parse_url['path'])>0)
	    {
	        $temp_url.=$arr_parse_url['path'];
	    }
	    if(isset($arr_parse_url['query']) && strlen($arr_parse_url['query'])>0)
	    {
	        $temp_url.='?'.$arr_parse_url['query'];
	    }

        //$temp_url = 'ftp://172.17.99.4/20180125/5a69fac7136390d66c51461df3c7afb8/5a68cd64dac2776b8955f1c32afc37a5.ts';
        //$this->asst_info['media']['cdn_info'] = np_guid_rand();
	    
	    $xml_str = '<?xml version="1.0" encoding="utf-8"?>';
	    $xml_str.= '<TransferContent ';
	    $xml_str.=     'providerID="coship" ';
	    $xml_str.=     'assetID="'.$this->asst_info['media']['cdn_info'].'" ';
	    $xml_str.=     'contentType="VOD" ';
	    $xml_str.=     'volumeName="coship" ';
	    $xml_str.=     'responseURL="'.$bk_web_url.'" ';
	    $xml_str.=     'interval="5" ';
	    $xml_str.= '>';
	    $xml_str.=     '<Input ';
	    $xml_str.=         'transferBitRate="'.$info['media']['base_info']['nns_kbps'].'" ';
	    $xml_str.=         'isEncrypted="true" ';
	    $xml_str.=         'codec="h264" ';
	    $xml_str.=         'format ="'.$info['media']['base_info']['nns_filetype'].'" ';
	    $xml_str.=         'sourceURL="'.$temp_url.'" ';
	    $xml_str.=         'userName="'.$temp_username.'" ';
	    $xml_str.=         'password="'.$temp_password.'" ';
	    $xml_str.=      '/>';
	    $xml_str.= '</TransferContent>';
	    /*******调用统一注入方法******/
	    $execute_info = array(
	        'nns_task_type' =>'Movie',
	        'nns_task_id' => $this->c2_task_info['nns_id'],
	        'nns_task_name' => $this->c2_task_info['nns_name'],
	        'nns_action' => $action, //行为动作
	        'nns_content' => $xml_str,//注入XML内容
	    );
	    return $this->execute($execute_info);
	}

    //EPG删除
    private function media_destroy($action)
    {
        //反馈地址
        global $g_bk_web_url;
        $bk_web_url = $g_bk_web_url;
        unset($g_bk_web_url);
        $bk_web_url = trim(trim(trim($bk_web_url,'\\'),'/'));
        $bk_web_url.="/v2/ns_api/gdgd_xiaole/delivery/coship/notify_destory.php";
        //构造删除CDN的基地址
        $str_cdn_send_mode_url = $this->arr_sp_config['nns_config']['cdn_send_mode_url'];
        $str_cdn_send_mode_url = substr($str_cdn_send_mode_url,0,strlen($str_cdn_send_mode_url) - strlen(strrchr($str_cdn_send_mode_url, '/')) + 1);
        $this->arr_sp_config['nns_config']['cdn_send_mode_url'] = $str_cdn_send_mode_url . 'DeleteContent';
        //构造XML
        $info = $this->asst_info;
        $str_xml = '<?xml version="1.0" encoding="utf-8"?>';
        $str_xml.= '<DeleteContent
                        providerID="coship"
                        assetID="' . $info['media']['cdn_info'] . '"
                        contentType="VOD"
                        reasonCode="201"
                        volumeName="coship"
                        responseURL="' . $bk_web_url . '"
                   >';
        $str_xml.= '<Input
                        transferBitRate="' . $info['media']['base_info']['nns_kbps'] . '"
                        codec="h264"
                        format ="ts"
                    />';
        $str_xml.= '</DeleteContent>';
        //发送HTTP请求
        return $this->execute(array(
            'nns_task_type' =>'Movie',
            'nns_task_id' => $this->c2_task_info['nns_id'],
            'nns_task_name' => $this->c2_task_info['nns_name'],
            'nns_action' => $action,
            'nns_content' => $str_xml,
        ));
    }
}